const Koa = require('koa');
const cors = require('koa2-cors');
const app = new Koa();
const views = require('koa-views');
const json = require('koa-json');
const onerror = require('koa-onerror');
const koaBody = require('koa-body');
const path = require('path');
const logger = require('koa-logger');
const jwtKoa = require('koa-jwt');

const router = require('./routes/index');
const uploadConfig = require('./controller/common/upload');

// 路径代理
global.$p = function(name) {
    return path.resolve(__dirname, name)
}
// const secret = 'tokenSecret'
// app.use(jwtKoa({secret}).unless({
//         path: [/^\/login/] //数组中的路径不需要通过jwt验证
//     }))
// 跨域处理
app.use(cors());

// 错误警告
onerror(app);

// 解析接收数据类型
app.use(koaBody(uploadConfig.config));

app.use(json());
app.use(logger());
// 声明静态文件位置
app.use(require('koa-static')(__dirname + '/public'));
// 声明模版存放位置
app.use(views(__dirname + '/views', {
  extension: 'ejs'
}));

// 日志管理
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`日志管理:${ctx.method} ${ctx.url} - ${ms}ms`)
});

// 路由
router(app);

// 错误监听
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app;
